#include "gwbase/base/path.h"

#include <assert.h>

namespace dicom {
namespace path {
namespace {

bool StartWithSep(const std::string& path) {
  if (path.empty())
    return false;
  char c = path[0];
  return (c == '/');
}

bool EndWithSep(const std::string& path) {
  if (path.empty())
    return false;

  char c = path[path.size()-1];
  return (c == '/');
}

std::string CutLastPart(const std::string& s, char sep) 
{
  if (s.empty())
    return s;

  size_t pos = s.find_last_of(sep, s.size());
  if (pos == std::string::npos)
    return s;

  if (pos == s.size()-1)
    return "";

  return s.substr(pos+1, s.size() - pos - 1);
}
}

std::string Join(const std::string& parent, const std::string& child) {
  if (parent.empty())
    return child;
  if (child.empty())
    return parent;

  if (EndWithSep(parent) || StartWithSep(child))
    return parent + child;
  return parent + "/" + child;
}

std::string Basename(const std::string& path) {
  return CutLastPart(path, '/');
}

std::string Extension(const std::string& path) {
  std::string basename = Basename(path);
  std::string last_part = CutLastPart(basename, '.');
  if (last_part == basename)
    return "";
  return last_part;
}

std::string Parent(const std::string& path) {
  std::string basename = Basename(path);

  // no parent
  if (path.size() == basename.size())
    return "";

  // parent is roort dir?
  if (basename.size() == path.size()-1 && StartWithSep(path)) {
    return "/";
  }

  return path.substr(0, path.size() - basename.size() - 1);
}

}
}

